package com.ocom.webapi.controller;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.entity.card.EntityXfAccountType;
import com.ocom.common.entity.card.EntityXfMealTime;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.GetMealDetailListBRequest;
import com.ocom.common.request.payconfig.GetTollPointInfoRequest;
import com.ocom.common.request.web.ConsTimeConfigOnShowRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.MealDetailBVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.business.PayCenterService;
import com.ocom.webapi.feign.PayConfigClientService;
import com.ocom.webapi.po.PayCenterVo;
import com.ocom.webapi.service.PayConfigService;
import com.ocom.webapi.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
@RestController
public class PayConfigController {

    @Autowired
    private PayConfigService payConfigService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private PayCenterService payCenterService;


    /**
     * 餐段列表（MealNameMap/onShow）
     * */
    @GetMapping(PayConfigUrl.URLP_PayConfig_MealPageOnShow)
    public Result MealPageOnShow(){
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        return payConfigService.MealPageOnShow(yoCiUser.getComId());
    }

    /**
     * 餐段新增（MealPage/add）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MealPageAdd)
    public Result MealPageAdd(@Validated @RequestBody MealPageAddVo mealPageAddVo){
        if (mealPageAddVo.getComId() == null || mealPageAddVo.getComId() < 1 ||
                mealPageAddVo.getMealNo().isEmpty() || mealPageAddVo.getMealName().isEmpty()){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        mealPageAddVo.setComId(yoCiUser.getComId());
        return payConfigService.MealPageAdd(mealPageAddVo);
    }

    /**
     * 餐段修改（MealPage/modify）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MealPageModify)
    public Result MealPageModify(@Validated @RequestBody MealPageModifyVo mealPageModifyVo) {
        if (mealPageModifyVo.getComId() == null || mealPageModifyVo.getComId() < 1 || mealPageModifyVo.getMealId() == null ||
                mealPageModifyVo.getMealId() < 1 || mealPageModifyVo.getMealNo().isEmpty() || mealPageModifyVo.getMealName().isEmpty()) {
            return ResultUtil.error(ResultEnum.Err_203);
        }
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        mealPageModifyVo.setComId(yoCiUser.getComId());
        return payConfigService.MealPageModify(mealPageModifyVo);
    }


    /**
     * 商户（MerchPage/Info）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MerchPageInfo)
    public Result MerchPageInfo(@RequestBody JSONObject jsonObject){
        Result result=payConfigClientService.MerchPageInfo(jsonObject.getLong("comId"),jsonObject.getInteger("merchId"));
        if(result.getCode()!=200){
            return ResultUtil.error(result.getCode());
        }
        Map<String,Object> map=new HashMap<>();
        map.put("company",result.getData());

        JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(result.getData()));
        PayCenterVo payCenterVo = null ;
        map.put("payCenterVo",null);
        String companyId = jsonObject1.getString("companyId");
        if(!CommonUtil.isNull(companyId)){
            payCenterVo  =payCenterService.merchInfo(jsonObject.getLong("comId"),companyId);
            if(payCenterVo!=null)
            map.put("payCenterVo",payCenterVo.getData());
        }
        return ResultUtil.success(map);
    }

    /**
     * 商户列表（MerchPage/onShow）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MerchPageOnShow)
    public Result MerchPageOnShow(@Validated @RequestBody MerchPageGetVo vo){
        YoCiUser yoCiUser= SecurityUtils.getYoCiUser();
        if(yoCiUser.getRole()==41l || yoCiUser.getRole()==42l){
            vo.setParentMerchId(yoCiUser.getMerchId());
        }
        return payConfigService.MerchPageOnShow(vo);
    }

    /**
     * 商户新增（MerchPage/add）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MerchPageAdd)
    public Result MerchPageAdd(@Validated @RequestBody MerchPageAddVo merchPageAddVo){
        if (merchPageAddVo.getComId() == null || merchPageAddVo.getComId() < 1 || merchPageAddVo.getMerchName().isEmpty()||
        merchPageAddVo.getParentMerchId() == null || merchPageAddVo.getParentMerchId() < 0) {
            return ResultUtil.error(ResultEnum.Err_203);
        }
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        merchPageAddVo.setComId(yoCiUser.getComId());
        return payConfigService.MerchPageAdd(merchPageAddVo);
    }



    /**
     * 商户修改（MerchPage/modify）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MerchPageModify)
    public Result MerchPageModify(@Validated @RequestBody MerchPageModifyVo merchPageModifyVo){
        if (merchPageModifyVo.getComId() == null || merchPageModifyVo.getComId() < 1 || merchPageModifyVo.getMerchName().isEmpty()||
                merchPageModifyVo.getParentMerchId() == null  ||
            merchPageModifyVo.getMerchId() < 0 ) {
            return ResultUtil.error(ResultEnum.Err_203);
        }
        if(merchPageModifyVo.getMerchId()==0){

        }
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        merchPageModifyVo.setComId(yoCiUser.getComId());
        return payConfigService.MerchPageModify(merchPageModifyVo);
    }


    /**
     * 餐段删除（MealPage/delete）
     * */
    @PostMapping(PayConfigUrl.URLP_PayConfig_MealPageDelete)
    public Result MealPageDelete(@Validated @RequestBody MealPageDeleteVo mealPageDeleteVo){
        if (mealPageDeleteVo.getComId() == null || mealPageDeleteVo.getComId() < 1 || mealPageDeleteVo.getMealNo().isEmpty()) {
            return ResultUtil.error(ResultEnum.Err_203);
        }
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        mealPageDeleteVo.setComId(yoCiUser.getComId());
        return payConfigService.MealPageDelete(mealPageDeleteVo);
    }

    /**
     * 添加缴费账户
     * */
    @PostMapping(PayConfigUrl.Url_FeeAccountAdd)
    public Result newFeeAccount(@RequestBody @Validated EntityXfMerchantInfo entityXfMerchantInfo){
//        if (entityXfMerchantInfo.getComId() == null || entityXfMerchantInfo.getComId() < 0 ){
//            return ResultUtil.error(ResultEnum.Err_203);
//        }
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        entityXfMerchantInfo.setComId(yoCiUser.getComId());
        entityXfMerchantInfo.setFeeFlag(1);//启用
        entityXfMerchantInfo.setParentMerchId(-8);
        entityXfMerchantInfo.setCreateTime(new Date());
        entityXfMerchantInfo.setCreateUser(entityXfMerchantInfo.getCreateUser());
        entityXfMerchantInfo.setUpdateUser(entityXfMerchantInfo.getUpdateUser());
        return payConfigClientService.addFeeAccount(entityXfMerchantInfo);
    }

    /**
     * 获取所有可用缴费账户
     * @param jsonObject
     * @return
     */
    @PostMapping(PayConfigUrl.URL_GetAllAccount)
    public Result getAllAccount(@RequestBody JSONObject jsonObject){
        return payConfigClientService.getAllAccount(jsonObject.getLong("comId"));
    }

    /**
     * 缴费账户列表
     * @param jsonObject
     * @return
     */
    @PostMapping(PayConfigUrl.URL_FeeAccountList)
    public Result getFeeAccountList(@RequestBody JSONObject jsonObject){
        return payConfigClientService.getFeeAccountList(jsonObject.getLong("comId"));
    }

    /**
     * 缴费商户列表
     * @param jsonObject
     * @return
     */
    @PostMapping(PayConfigUrl.URL_FeeMerchList)
    public Result getFeeMerchList(@RequestBody JSONObject jsonObject){
        return payConfigClientService.getFeeMerchList(jsonObject.getLong("comId"));
    }

    /**
     * 15.5修改缴费账户
     * @param request
     * @return
     */
    @PostMapping(PayConfigUrl.URL_updateFeeAccount)
    public Result updateFeeAccount(@RequestBody EntityXfMerchantInfo request){
        return payConfigClientService.updateFeeAccount(request);
    }

    /**
     * 15.3改变商户缴费状态
     * @param request
     * @return
     */
    @PostMapping(PayConfigUrl.URL_changeMerchStatus)
    public Result changeMerchStatus(@RequestBody EntityXfMerchantInfo request){
        return payConfigClientService.changeMerchStatus(request);
    }

    /**
     * 3.1.B.2餐段新增（MealPointPage/add）
     * @return
     */
    @PostMapping(WebApiServiceUrl.URL_MealPointPageAdd)
    public Result mealPointPageAdd(@RequestBody MealPointPageAddVo mealPointPageAddVo){
        if (mealPointPageAddVo.getComId() == null || mealPointPageAddVo.getComId() < 1 ||
                mealPointPageAddVo.getMealNo().isEmpty()){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        ConsTimeConfigOnShowRequest configOnShowRequest = new ConsTimeConfigOnShowRequest();
        configOnShowRequest.setSize(10);
        configOnShowRequest.setPage(1);
        configOnShowRequest.setMealNo(mealPointPageAddVo.getMealNo());
        configOnShowRequest.setPointId(mealPointPageAddVo.getPointId());
        configOnShowRequest.setAccTypeId(mealPointPageAddVo.getAccTypeId());
        configOnShowRequest.setComId(mealPointPageAddVo.getComId());
        Result result = this.payConfigClientService.GetMealTimeInfo(configOnShowRequest);
        if(!result.getCode().equals(200)){
            return result;
        }

        JSONObject map = JSON.parseObject(JSON.toJSONString(result.getData()));
        if(!map.getInteger("total").equals(0)){
            return ResultUtil.error(ResultEnum.Err_3115);
        }
        EntityXfMealTime entityXfMealTime = new EntityXfMealTime();
        entityXfMealTime.setComId(mealPointPageAddVo.getComId());
        entityXfMealTime.setMealNo(mealPointPageAddVo.getMealNo());
        entityXfMealTime.setBeginTime(mealPointPageAddVo.getStartTime());
        entityXfMealTime.setEndTime(mealPointPageAddVo.getEndTime());
        entityXfMealTime.setCreateUser(SecurityUtils.getUsername());
        entityXfMealTime.setBeforeHour(mealPointPageAddVo.getBeforeHour());
        entityXfMealTime.setAllowDays(mealPointPageAddVo.getAllowDays());
        entityXfMealTime.setAllowMinute(mealPointPageAddVo.getAllowMinute());
        entityXfMealTime.setAdvanceMoney(new BigDecimal(0));
        entityXfMealTime.setAccTypeId(mealPointPageAddVo.getAccTypeId());
        entityXfMealTime.setPointId(mealPointPageAddVo.getPointId());
        entityXfMealTime.setConsTimeZone(0);
        return payConfigClientService.AddMealTimeInfo(entityXfMealTime);
    }

    /**
     * 3.1.B.3餐段修改（MealPointPage/modify）
     * @return
     */
    @PostMapping(WebApiServiceUrl.URL_MealPointPageModify)
    public Result mealPointPageModify(@RequestBody MealPointPageModifyVo mealPointPageModifyVo){
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        EntityXfMealTime entityXfMealTime = Convert.convert(EntityXfMealTime.class,mealPointPageModifyVo);
        entityXfMealTime.setComId(yoCiUser.getComId());
        return payConfigClientService.UpdateMealTimeInfo(entityXfMealTime);
    }

    /**
     * 3.1.B.4餐段删除（MealPointPage/delete）
     * @return
     */
    @PostMapping(WebApiServiceUrl.URL_MealPointPageDelete)
    public Result mealPointPageDelete(@RequestBody MealPointPageDeleteVo mealPointPageDeleteVo){
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        HashMap<String,Object> map = new HashMap<>();
        map.put("comId",yoCiUser.getComId());
        map.put("id",mealPointPageDeleteVo.getId());
        return payConfigClientService.DeleteMealTimeInfo(map);
    }

    /**
     * 3.1.B.1餐段列表（MealPointPage/onShow）
     * @param mealPointPageOnShowVo
     * @return
     */
    @PostMapping(WebApiServiceUrl.URL_MealPointPageOnShow)
    public Result mealPointPageOnShow(@RequestBody MealPointPageOnShowVo mealPointPageOnShowVo){
        GetMealDetailListBRequest getMealDetailListRequest = Convert.convert(GetMealDetailListBRequest.class,mealPointPageOnShowVo);
        Result<List<MealDetailBVo>> result = this.payConfigClientService.getMealDetailListB(getMealDetailListRequest);
        if(!result.getCode().equals(200)){
            return result;
        }
        result.getData().forEach(mealDetail->{
            GetTollPointInfoRequest tollPointInfoRequest = new GetTollPointInfoRequest();
            tollPointInfoRequest.setCom_id(mealDetail.getComId());
            tollPointInfoRequest.setPoint_id(mealPointPageOnShowVo.getPointId());
            tollPointInfoRequest.setSize(1);
            Result result1 = this.payConfigClientService.getTollPointInfo(tollPointInfoRequest);
            if(result1.getCode().equals(200)){
                LinkedHashMap data = (LinkedHashMap)result1.getData();
                List l =  (List)data.get("list");

                if(!ObjectUtils.isEmpty(l)) {
                    for (Object obj: l){
                        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));
                        if(jsonObject.getInteger("pointId").equals(mealDetail.getPointId())){
                            mealDetail.setPointName(jsonObject.getString("pointName"));
                            break;
                        }
                    }
                }
            }
            Result result2 = this.payConfigClientService.GetXFAccountType(mealDetail.getComId());
            if(result2.getCode()==200){
                List<EntityXfAccountType> list = JSON.parseArray(JSON.toJSONString(result2.getData()),EntityXfAccountType.class);
                for (EntityXfAccountType entityXfAccountType: list) {
                    if(entityXfAccountType.getAccTypeId().equals(mealDetail.getAccTypeId())){
                        mealDetail.setAccTypeName(entityXfAccountType.getAccTypeName());
                        break;
                    }
                }
            }
        });
        return result;
    }
}
